<template>
  <div>
    <h1 style="font-size: 30px;margin-bottom:10px">修改Blog</h1>
    <div id="edit">
      <el-row :gutter="20">
        <el-col :span="18">
          <el-input
            v-model="blog.title"
            placeholder="请输入标题"
            maxlength="20"
            show-word-limit
          ></el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="$save">修改并保存</el-button>
          <el-dialog title="保存Blog" :visible.sync="dialogFormVisible">
            <form name="form">
              <p>请选择Blog类型</p>
              <el-radio-group v-model="classifId">
                <el-radio
                  :label="c.classifyId"
                  v-for="c in classifies"
                  :key="c.classifyId"
                >
                  <span>{{ c.classifyName }}</span>
                </el-radio>
              </el-radio-group>
              <p>请选择Blog标签</p>
              <el-checkbox-group v-model="tagIdList">
                <el-checkbox v-for="t in tags" :key="t.tagId" :label="t.tagId"
                  >{{ t.tagName }}
                </el-checkbox>
              </el-checkbox-group>

              <p>请选择Blog封面</p>
              <el-upload
                class="upload-demo"
                :limit="1"
                :file-list="fileList"
                ref="upload"
                :action="path"
                name="blogimg"
                :on-success="handleSuccess"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :on-preview="preview"
              >
                <el-button type="primary" size="small" slot="trigger"
                  >选取文件
                </el-button>
                <div solt="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不能超过3M
                </div>
              </el-upload>
            </form>
            <el-row class="btngroup">
              <el-button @click="saveToDraft" type="info"
                >保存放入草稿箱</el-button
              >
              <el-button @click="saveAndPublish">保存并发布</el-button>
            </el-row>
          </el-dialog>
        </el-col>
      </el-row>

      <mavon-editor
        :ishljs="true"
        style="max-height: 600px; margin-top: 20px"
        fontSize="15px"
        ref="md"
        @imgAdd="$ImgAdd"
        @save="$save"
        v-model="blog.content"
        @imgDel="$ImgDel"
        codeStyle="ocean"
        :scrollStyle="true"
      >
      </mavon-editor>
    </div>
  </div>
</template>

<script>
import { mavonEditor } from "mavon-editor";
import "mavon-editor/dist/css/index.css";
export default {
  name: "EditBlog",
  components: {
    mavonEditor,
  },
  data() {
    return {
      path: this.axios.defaults.baseURL + "/blog/upload/cover",
      imgPath: this.axios.defaults.baseURL,
      dialogFormVisible: false,
      blog: {},
      tags: [],
      tagIdList: [],
      classifies: [],
      classifId: "",
      fileList: [],
      file: {},
      imgurl: "",
      imgshow: false,
      formdata: {},
    };
  },
  methods: {
    loadblog(id) {
      this.axios.get(`/blog/${id}`).then((res) => {
        this.blog = res.data.blog;
        this.classifId = this.blog.classify.classifyId;
        var tags = new Array(this.blog.tagList.length);
        for (var i = 0; i < this.blog.tagList.length; i++) {
          this.tagIdList.push(this.blog.tagList[i].tagId);
        }
        if (this.blog.blogCover != "" && this.blog.blogCover != undefined) {
          this.imgshow = true;
          this.file.name = this.blog.blogCover;
          this.file.url = this.imgPath + this.blog.blogCover;
          this.fileList.push(this.file);
          this.imgurl = this.imgPath + this.blog.blogCover;
        } else {
          this.fileList.length = 0;
        }
      });
    },
    $ImgAdd(pos, $file) {
      var formdata = new FormData();
      formdata.append("image", $file);
      this.axios.post("/blog/upload/img", formdata).then((res) => {
        if (res.status == 200) {
          this.$message.success("上传成功");
          this.$refs.md.$img2Url(pos, res.data.url);
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    $ImgDel(pos, $file) {
      let webrootlen = this.axios.defaults.baseURL.length;
      let path = pos[0].substring(webrootlen);
      let formdata = new FormData();
      formdata.append("imgPath", path);
      this.axios.post("/blog/remove/img", formdata).then((res) => {
        if (res.data.success) {
          this.$message.success(res.data.msg);
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    $save() {
      this.dialogFormVisible = true;
    },
    handleSuccess(res) {
      if (res.success) {
        this.$message.success(res.msg);
        this.blog.blogCover = res.path;
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前只能选择1个图片文件，本次选择了${files.length}个文件，共选择了${
          files.length + fileList.length
        }个文件`
      );
    },
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt3M = file.size / 1024 / 1024 < 3;
      if (!isJPG) {
        this.$message.error("上传封面文件只能是JPG/PNG格式");
      }
      if (!isLt3M) {
        this.$message.error("上传封面文件大小不能超过3MB");
      }
      return isJPG && isLt3M;
    },
    beforeRemove(file) {
      return this.$confirm(`确认移除${file.name}？`);
    },

    handleRemove(file) {
      let formdata = new FormData();
      formdata.append("imgPath", file.name);
      this.axios.post("/blog/remove/img", formdata).then((res) => {
        if (res.data.success) {
          this.$message.success(res.data.msg);
        } else {
          this.$message.error(res.data.msg);
        }
      });
      this.blog.blogCover = "";
    },
    preview(file) {
      window.open(file.url);
    },

    getFormData() {
      let formdata = new FormData();
      formdata.append("blogId", this.blog.blogId);
      formdata.append("title", this.blog.title);
      formdata.append("content", this.blog.content);
      formdata.append("userId", this.blog.userId);
      formdata.append("isDraft", this.blog.isDraft);
      formdata.append("classifyId", this.classifId);
      formdata.append("tags", this.tagIdList);
      formdata.append("isCovery", this.blog.isCovery);
      formdata.append("isDraft", this.blog.isDraft);
      formdata.append("blogCover", this.blog.blogCover);
      if (this.tagIdList.length == 0) {
        this.$message.error("请选择标签");
      }
      return formdata;
    },
    saveToDraft() {
      this.blog.isCovery = 0;
      this.blog.isDraft = 1;
      let formData = this.getFormData();
      this.axios.post("/blog/update", formData).then((res) => {
        if (res.data.success) {
          this.$message.success("保存成功，已放入草稿箱");
          this.dialogFormVisible = false;
          this.$router.push("/manage/draft");
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    saveAndPublish() {
      this.blog.isCovery = 0;
      this.blog.isDraft = 0;
      let formData = this.getFormData();
      this.axios.post("/blog/update", formData).then((res) => {
        if (res.data.success) {
          this.$message.success("修改成功");
          this.dialogFormVisible = false;
          this.$router.push("../BlogList");
        } else {
          this.$message.error("修改失败");
        }
      });
    },
    loadTagList() {
      this.axios.get("/tag/select").then((res) => {
        this.tags = res.data.data;
      });
    },
    loadClassify() {
      this.axios.get("/classify/select").then((res) => {
        this.classifies = res.data.data;
      });
    },
  },
  created() {
    this.loadblog(this.$route.params.id);
    this.loadTagList();
    this.loadClassify();
  },
};
</script>

<style>
#edit .btngroup {
  text-align: center;
  margin-top: 20px;
}

#edit .el-radio-group {
  font-size: 17px;
  margin: 10px 0px 20px 0px;
}

#edit .el-checkbox-group {
  margin: 10px 0px 20px 0px;
}

#edit .el-checkbox-group .el-checkbox {
  font-size: 17px;
  margin-bottom: 6px;
}

#edit .el-upload {
  margin-top: 10px;
}
</style>
